<template>
  <div class="add-product">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑产品' : '添加产品' }}</h2>
      <p>{{ isEdit ? '修改产品信息' : '创建新的产品信息' }}</p>
    </div>
    
    <div class="content-section">
      <form @submit.prevent="submitForm" class="product-form">
        <div class="form-grid">
          <!-- 基本信息 -->
          <div class="form-section">
            <h3>基本信息</h3>
            <div class="form-row">
              <div class="form-group">
                <label for="serialNumber">商品编号 *</label>
                <input 
                  type="text" 
                  id="serialNumber" 
                  v-model="form.serial_number" 
                  required 
                  placeholder="请输入商品编号"
                  class="form-control">
              </div>
              
              <div class="form-group">
                <label for="productName">产品名称 *</label>
                <input 
                  type="text" 
                  id="productName" 
                  v-model="form.name" 
                  required 
                  placeholder="请输入产品名称"
                  class="form-control">
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label for="brand">品牌 *</label>
                <select id="brand" v-model="form.brand_id" required class="form-control">
                  <option value="">请选择品牌</option>
                  <option v-for="brand in brands" :key="brand.brand_id" :value="brand.brand_id" :disabled="brand.status === 0 || brand.status === '0'">
                    {{ brand.brand_name }}{{ brand.status === 0 || brand.status === '0' ? ' (已禁用)' : '' }}
                  </option>
                </select>
              </div>
              
              <div class="form-group">
                <label for="category">分类 *</label>
                <select id="category" v-model="form.type_id" required class="form-control">
                  <option value="">请选择分类</option>
                  <option v-for="type in types" :key="type.typeId" :value="type.typeId" :disabled="type.status === 0 || type.status === '0'">
                    {{ type.typeName }}{{ type.status === 0 || type.status === '0' ? ' (已禁用)' : '' }}
                  </option>
                </select>
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label for="color">颜色 *</label>
                <select id="color" v-model="form.color_id" required class="form-control">
                  <option value="">请选择颜色</option>
                  <option v-for="color in colors" :key="color.colorId" :value="color.colorId" :disabled="color.status === 0 || color.status === '0'">
                    {{ color.colorName }}{{ color.status === 0 || color.status === '0' ? ' (已禁用)' : '' }}
                  </option>
                </select>
              </div>
              
              <div class="form-group">
                <label for="gender">性别 *</label>
                <select id="gender" v-model="form.gender" required class="form-control">
                  <option value="男">男</option>
                  <option value="女">女</option>
                  <option value="男女通用">男女通用</option>
                </select>
              </div>
            </div>
            
            <div class="form-group">
              <label for="description">产品描述</label>
              <textarea 
                id="description" 
                v-model="form.description" 
                placeholder="请输入产品描述"
                class="form-control"
                rows="3"></textarea>
            </div>
            
            <div class="form-group">
              <label for="detailedInfo">详细信息</label>
              <textarea 
                id="detailedInfo" 
                v-model="form.detailed_info" 
                placeholder="请输入详细信息（材质、工艺等）"
                class="form-control"
                rows="3"></textarea>
            </div>
          </div>
          
          <!-- 价格信息 -->
          <div class="form-section">
            <h3>价格信息</h3>
            <div class="form-row">
              <div class="form-group">
                <label for="price">原价 *</label>
                <input 
                  type="number" 
                  id="price" 
                  v-model.number="form.price" 
                  required 
                  min="0" 
                  step="0.01"
                  placeholder="0.00"
                  class="form-control">
              </div>
              
              <div class="form-group">
                <label for="discountPrice">折扣价</label>
                <input 
                  type="number" 
                  id="discountPrice" 
                  v-model.number="form.discount_price" 
                  min="0" 
                  step="0.01"
                  placeholder="0.00"
                  class="form-control">
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label for="launchDate">上市日期</label>
                <input 
                  type="date" 
                  id="launchDate" 
                  v-model="form.launch_date" 
                  class="form-control">
              </div>
              
              <div class="form-group">
                <label for="itemPoints">商品积分</label>
                <input 
                  type="number" 
                  id="itemPoints" 
                  v-model.number="form.item_points" 
                  min="0"
                  placeholder="0"
                  class="form-control">
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label for="salesVolume">销量</label>
                <input 
                  type="number" 
                  id="salesVolume" 
                  v-model.number="form.sales_volume" 
                  min="0"
                  placeholder="0"
                  class="form-control">
              </div>
              
              <div class="form-group">
                <label for="status">状态 *</label>
                <select id="status" v-model="form.status" required class="form-control">
                  <option value="1">上架</option>
                  <option value="0">下架</option>
                </select>
              </div>
            </div>
          </div>
          
          <!-- 其他信息 -->
          <div class="form-section">
            <h3>其他信息</h3>
            <div class="form-row">
              <div class="form-group">
                <label for="originPlace">产地</label>
                <input 
                  type="text" 
                  id="originPlace" 
                  v-model="form.origin_place" 
                  placeholder="请输入产地"
                  class="form-control">
              </div>
            </div>
            
            <div class="form-group">
              <label for="productImage">商品图片URL</label>
              <input 
                type="url" 
                id="productImage" 
                v-model="form.product_image_url" 
                placeholder="请输入商品图片URL"
                class="form-control">
            </div>
          </div>

          <!-- 图片上传管理 -->
          <div class="form-section">
            <h3>商品图片</h3>
            <div v-if="!savedShoeId && !isEdit" class="upload-placeholder">
              <p class="placeholder-text">
                <i class="icon">📷</i>
                请先保存商品信息，然后可以上传商品图片
              </p>
            </div>
            <ProductImageUpload 
              v-else
              :shoe-id="savedShoeId || (isEdit ? productData.shoeId : null)"
              @show-message="showToast"
            />
          </div>
        </div>
        
        <div class="form-actions">
          <button type="button" @click="goBack" class="btn btn-secondary">
            <i class="icon">↩️</i>
            返回
          </button>
          <button type="submit" class="btn btn-primary" :disabled="submitting">
            <i class="icon">{{ submitting ? '⏳' : '💾' }}</i>
            {{ submitting ? '保存中...' : (isEdit ? '更新产品' : '创建产品') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import ProductImageUpload from './ProductImageUpload.vue'

export default {
  name: 'AddProduct',
  components: {
    ProductImageUpload
  },
  props: {
    productData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      submitting: false,
      savedShoeId: null, // 保存后的商品ID，用于图片上传
      form: {
        serial_number: '',
        name: '',
        brand_id: '',
        type_id: '',
        color_id: '',
        price: 0,
        discount_price: 0,
        launch_date: '',
        origin_place: '',
        gender: '男女通用',
        description: '',
        detailed_info: '',
        item_points: 0,
        status: 1,
        product_image_url: '',
        sales_volume: 0
      },
      brands: [],
      types: [],
      colors: [],
      sizes: [
        { id: 1, value: '35' },
        { id: 2, value: '36' },
        { id: 3, value: '37' },
        { id: 4, value: '38' },
        { id: 5, value: '39' },
        { id: 6, value: '40' },
        { id: 7, value: '41' },
        { id: 8, value: '42' },
        { id: 9, value: '43' },
        { id: 10, value: '44' },
        { id: 11, value: '45' }
      ]
    };
  },
  computed: {
    isEdit() {
      return this.productData && this.productData.id;
    }
  },
  async mounted() {
    await this.loadSelectOptions();
    if (this.isEdit) {
      this.loadProductData();
    }
  },
  methods: {
    async loadSelectOptions() {
      try {
        await Promise.all([
          this.loadBrands(),
          this.loadTypes(),
          this.loadColors()
        ]);
      } catch (error) {
        console.error('加载选择项数据失败:', error);
      }
    },

    async loadBrands() {
      try {
        const response = await axios.get('/api/brands');
        if (response.data && response.data.code === 200) {
          this.brands = response.data.data || [];
        } else {
          this.brands = response.data || [];
        }
        console.log('加载品牌数据:', this.brands);
      } catch (error) {
        console.error('加载品牌列表失败:', error);
        // 使用示例数据作为后备
        this.brands = [
          { brand_id: 1, brand_name: 'Nike' },
          { brand_id: 2, brand_name: 'Adidas' },
          { brand_id: 3, brand_name: 'Converse' }
        ];
      }
    },

    async loadTypes() {
      try {
        const response = await axios.get('/api/types');
        if (response.data && response.data.code === 200) {
          this.types = response.data.data || [];
        } else {
          this.types = response.data || [];
        }
        console.log('加载分类数据:', this.types);
      } catch (error) {
        console.error('加载分类列表失败:', error);
        // 使用示例数据作为后备
        this.types = [
          { typeId: 1, typeName: '运动鞋', status: '1' },
          { typeId: 2, typeName: '跑步鞋', status: '1' },
          { typeId: 3, typeName: '帆布鞋', status: '1' }
        ];
      }
    },

    async loadColors() {
      try {
        const response = await axios.get('/api/colors');
        if (response.data && response.data.code === 200) {
          this.colors = response.data.data || [];
        } else {
          this.colors = response.data || [];
        }
        console.log('加载颜色数据:', this.colors);
      } catch (error) {
        console.error('加载颜色列表失败:', error);
        // 使用示例数据作为后备
        this.colors = [
          { colorId: 1, colorName: '黑色', status: '1' },
          { colorId: 2, colorName: '白色', status: '1' },
          { colorId: 3, colorName: '红色', status: '1' }
        ];
      }
    },

    loadProductData() {
      if (this.productData) {
        Object.assign(this.form, this.productData);
      }
    },
    
    async submitForm() {
      this.submitting = true;
      
      try {
        // 验证表单
        if (!this.validateForm()) {
          this.submitting = false;
          return;
        }
        
        // 这里应该调用后端API
        if (this.isEdit) {
          await this.updateProduct();
        } else {
          await this.createProduct();
        }
        
        this.showToast(this.isEdit ? '产品更新成功' : '产品创建成功', 'success');
        
        // 延迟返回列表页
        setTimeout(() => {
          this.goBack();
        }, 1500);
        
      } catch (error) {
        console.error('保存产品失败:', error);
        this.showToast('保存产品失败', 'error');
      } finally {
        this.submitting = false;
      }
    },
    
    validateForm() {
      if (!this.form.serial_number.trim()) {
        this.showToast('请输入商品编号', 'warning');
        return false;
      }
      
      if (!this.form.name.trim()) {
        this.showToast('请输入产品名称', 'warning');
        return false;
      }
      
      if (!this.form.brand_id || this.form.brand_id === '' || parseInt(this.form.brand_id) <= 0) {
        this.showToast('请选择品牌', 'warning');
        return false;
      }
      
      if (!this.form.type_id || this.form.type_id === '' || parseInt(this.form.type_id) <= 0) {
        this.showToast('请选择分类', 'warning');
        return false;
      }
      
      if (!this.form.color_id || this.form.color_id === '' || parseInt(this.form.color_id) <= 0) {
        this.showToast('请选择颜色', 'warning');
        return false;
      }
      
      if (this.form.price <= 0) {
        this.showToast('请输入有效的价格', 'warning');
        return false;
      }
      
      return true;
    },
    
    async createProduct() {
      const productData = {
        serialNumber: this.form.serial_number,
        name: this.form.name,
        price: parseFloat(this.form.price),
        discountPrice: this.form.discount_price ? parseFloat(this.form.discount_price) : null,
        launchDate: this.form.launch_date,
        originPlace: this.form.origin_place,
        gender: this.form.gender,
        description: this.form.description,
        detailedInfo: this.form.detailed_info,
        itemPoints: parseInt(this.form.item_points) || 0,
        status: this.form.status.toString(),
        productImageUrl: this.form.product_image_url,
        salesVolume: parseInt(this.form.sales_volume) || 0,
        colorId: parseInt(this.form.color_id) || null,
        brandId: parseInt(this.form.brand_id) || null,
        typeId: parseInt(this.form.type_id) || null
      };
      
      // 确保必需字段不为null
      if (!productData.brandId) {
        throw new Error('品牌ID不能为空');
      }
      if (!productData.typeId) {
        throw new Error('分类ID不能为空');
      }
      if (!productData.colorId) {
        throw new Error('颜色ID不能为空');
      }
      
      const response = await axios.post('/api/v1/shoes/add', productData);
      // 保存创建的商品ID，用于图片上传
      if (response.data && response.data.data && response.data.data.shoeId) {
        this.savedShoeId = response.data.data.shoeId;
      }
    },
    
    async updateProduct() {
      const productData = {
        shoeId: this.form.shoe_id || this.productData?.shoeId,
        serialNumber: this.form.serial_number,
        name: this.form.name,
        price: parseFloat(this.form.price),
        discountPrice: this.form.discount_price ? parseFloat(this.form.discount_price) : null,
        launchDate: this.form.launch_date,
        originPlace: this.form.origin_place,
        gender: this.form.gender,
        description: this.form.description,
        detailedInfo: this.form.detailed_info,
        itemPoints: parseInt(this.form.item_points) || 0,
        status: this.form.status.toString(),
        productImageUrl: this.form.product_image_url,
        salesVolume: parseInt(this.form.sales_volume) || 0,
        colorId: parseInt(this.form.color_id) || null,
        brandId: parseInt(this.form.brand_id) || null,
        typeId: parseInt(this.form.type_id) || null
      };
      
      // 确保必需字段不为null
      if (!productData.brandId) {
        throw new Error('品牌ID不能为空');
      }
      if (!productData.typeId) {
        throw new Error('分类ID不能为空');
      }
      if (!productData.colorId) {
        throw new Error('颜色ID不能为空');
      }
      
      await axios.post('/api/v1/shoes/update', productData);
    },
    
    goBack() {
      this.$emit('navigate', '产品列表');
    },
    
    showToast(message, type = 'info') {
      const toast = document.createElement('div');
      toast.className = `toast toast-${type}`;
      toast.textContent = message;
      
      Object.assign(toast.style, {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '12px 20px',
        borderRadius: '6px',
        color: 'white',
        fontSize: '14px',
        fontWeight: '500',
        zIndex: '10000',
        opacity: '0',
        transform: 'translateX(100%)',
        transition: 'all 0.3s ease',
        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)'
      });

      const colors = {
        success: '#10b981',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
      };
      
      toast.style.background = colors[type] || colors.info;
      document.body.appendChild(toast);
      
      setTimeout(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateX(0)';
      }, 100);
      
      setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(100%)';
        setTimeout(() => {
          if (document.body.contains(toast)) {
            document.body.removeChild(toast);
          }
        }, 300);
      }, 3000);
    }
  }
};
</script>

<style scoped>
.add-product {
  padding: 2rem;
  background: #f8fafc;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
  border: 1px solid #e5e7eb;
}

.page-header h2 {
  margin: 0 0 0.5rem 0;
  font-size: 1.875rem;
  color: #1f2937;
  font-weight: 700;
}

.page-header p {
  margin: 0;
  color: #6b7280;
  font-size: 1rem;
}

.content-section {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
}

.product-form {
  max-width: 1000px;
  margin: 0 auto;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 2rem;
  margin-bottom: 2rem;
}

.form-section {
  background: #f9fafb;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.form-section h3 {
  margin: 0 0 1.5rem 0;
  font-size: 1.125rem;
  color: #1f2937;
  font-weight: 600;
  border-bottom: 2px solid #3b82f6;
  padding-bottom: 0.5rem;
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #374151;
  font-size: 0.875rem;
}

.form-control {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 0.875rem;
  transition: all 0.2s ease;
  background: white;
}

.form-control:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-control:invalid {
  border-color: #ef4444;
}

textarea.form-control {
  resize: vertical;
  min-height: 5rem;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 0.75rem;
  padding-top: 1.5rem;
  border-top: 1px solid #e5e7eb;
}

.btn {
  display: inline-flex;
  align-items: center;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #2563eb;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.btn-secondary {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover {
  background: #e5e7eb;
  transform: translateY(-1px);
}

.btn .icon {
  margin-right: 0.5rem;
  font-size: 1rem;
}

.upload-placeholder {
  background: #f8fafc;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  margin-top: 1rem;
}

.placeholder-text {
  color: #6b7280;
  font-size: 0.875rem;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.placeholder-text .icon {
  font-size: 1.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-product {
    padding: 1rem;
  }
  
  .page-header {
    padding: 1.5rem;
    margin-bottom: 1.5rem;
  }
  
  .page-header h2 {
    font-size: 1.5rem;
  }
  
  .content-section {
    padding: 1.5rem;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 0.75rem;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-section {
    padding: 1rem;
  }
}
</style>